from django.http import HttpResponse, HttpResponseRedirect
from whoisspy.forms import RegistrationForm
from whoisspy.models import Player
from django.contrib.sites.models import Site
from django.core.mail import EmailMultiAlternatives
from django.contrib import messages, auth
from django.shortcuts import render_to_response
import hashlib

def register(request):
    if request.method == "POST":
        form = RegistrationForm(request.POST)

        if form.is_valid():
            new_user = form.save()
            new_user.is_active = False
            new_user.save()

            hash_obj = hashlib.sha1()
            hash_obj.update(new_user.username)
            confirmation_code = hash_obj.hexdigest()
            player = Player(user=new_user, confirmation_code=confirmation_code[0:9])
            player.save()

            send_registration_confirmation(new_user)

def send_registration_confirmation(user):
    profile = user.get_profile()
    current_site = Site.objects.get_current()
    subject, from_email, to = "Survey account activation", "no-reply@localhost", user.email

    link ="http://%s/account/confirm/%s"% (current_site.domain, str(profile.confirmation_code)+ "/" + user.username)
    text_content = "Hello and welcome to Who Is Spy. We have sent you this e-mail because you recently registered on Who Is Spy. Please click on the following link to activate your account. %s" % link
    html_content = "Hello and welcome to Who Is Spy.<br />We have sent you this e-mail because you recently registered on Who Is Spy.<br />Please click on the following link to activate your account.<br /><a href='%s'>%s</a>" % (link, link)
    msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
    msg.attach_alternative(html_content, "text/html")
    msg.send()

def login_view(request):
    if request.method == "POST":
        username_or_email = request.POST.get("username_or_email")
        password = request.POST.get("password")

        user = auth.authenticate(email=username_or_email, password=password)

        if user is not None and user.is_active:
            auth.login(request, user)
            if user.is_superuser:
                return HttpResponseRedirect("/admin")
            else:
                return HttpResponseRedirect("/account")
        else:
            return render_to_response("account/login.html", {'error':True}, context_instance=RequestContext(request))

        def confirm(request, con  ,)